﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// unity功能扩展
/// </summary>
public static class U3DExtension
{
    public static int IndexOf<T>(this T[] array, T item)
    {
        for (int idx = 0; idx < array.Length; ++idx)
        {
            if (array[idx].Equals(item))
            {
                return idx;
            }
        }
        return -1;
    }

    public static Transform FindChildRecursively(this Transform trans, params string[] names)
    {
        return DoFindChildRecursively(trans, names);
    }
    /// <summary>
    /// 指定节点下查找对象
    /// </summary>
    /// <param name="trans"></param>
    /// <param name="path">指定节点的路径</param>
    /// <param name="names">查找的名称清单</param>
    /// <returns></returns>
    public static Transform FindChildRecursivelyQuick(this Transform trans, string path, params string[] names)
    {
        Transform pathRoot = trans.FindChild(path);
        return pathRoot == null ? null : DoFindChildRecursively(pathRoot, names);
    }
    static Transform DoFindChildRecursively(Transform trans, string[] names)
    {
        var count = trans.childCount;
        for (int i = 0; i < count; i++)
        {
            Transform child = trans.GetChild(i);

            if (names.IndexOf(child.name) != -1)
            {
                return child;
            }
            else
            {
                Transform ret = DoFindChildRecursively(child, names);
                if (ret != null)
                {
                    return ret;
                }
            }
        }
        return null;
    }

    public static void SetCull(this GameObject obj, bool cull, bool recursively)
    {
        if (recursively)
        {
            foreach (Transform child in obj.transform)
            {
                child.gameObject.SetCull(cull, recursively);
            }
        }
        CanvasRenderer canvasRenderer = obj.GetComponent<CanvasRenderer>();
        if (canvasRenderer == null)
            return;
        canvasRenderer.cull = cull;
        Graphic graphic = obj.gameObject.GetComponent<Graphic>();
        if (graphic == null)
            return;
        if (!cull)
            graphic.SetAllDirty();
        //if (graphic is YImage)
        //{
        //    YImage img = graphic as YImage;
        //    img.cull = cull;
        //}
    }
}
